<?php
class Category
{
	public $Table="jlcategory";
	public $categoryid;
	public $categoryname;
	public $parent;
	public $position;
	
	function loadByKey($id)
	{
		$ob=new ClassConnect();
		$sql="select * from `".$this->Table."` where categoryid='".$id."'";
		$row=$ob->singleData($sql);
		if(count($row)>1)
			foreach($row as $key =>$item)
				$this->$key = $item;
		
	}
	
	function loadByItem($data)
	{
		foreach($data as $key =>$item)
			$this->$key = $item;
	}
	
	function getTable($dk="")
	{
		$ob=new ClassConnect();
		$sql="select * from `".$this->Table."` where 1=1 $dk";
		$data=$ob->mutiData($sql);
		return $data;
	}
	
	function getDeep()
	{
		$obj = new Category();
		$obj->loadByKey($this->categoryid);
		$deep = 0;
		while($obj->categoryid != "")
		{
			$obj->loadByKey($obj->parent);
			$deep++;
		}
		return $deep;
	}
	
	function getChild()
	{
		$where = " AND parent = '".$this->categoryid."' ORDER BY `jlcategory`.`position` ASC";
		return $this->getTable($where);
	}
	
	function getTree($id,&$data)
	{
		$obj = new Category();
		$obj->loadByKey($id);
		$child = $obj->getChild();
		if($id !="")
		{
			$data[] = $obj;
		}
		
		if(count($child))
		{
			foreach($child as $item)
			{
				$this->getTree($item['categoryid'],$data);
			}
		}
	}
	
	function getNextPos($cparent)
	{
		$ob=new ClassConnect();
		$sql="SELECT max(position) as max FROM `jlcategory` where parent='$cparent'";
		$row=$ob->singleData($sql);
		$max=$row['max'];
		return $max + 1;
	}
	
	function save($conn)
	{
		$ob=new ClassConnect();
		$obj = new Category();
		$field=array(
						"categoryid",
						"categoryname",
						"parent",
						"position"
						
					);
		$value=array(
						$this->categoryid,
						$this->categoryname,
						$this->parent,
						$this->position
			
					);
		$obj->loadByKey($this->categoryid);
		if($obj->categoryid =="")
		{
			
			return $ob->insertData($conn,$this->Table,$field,$value);
		}
		else
		{
			$where="categoryid = '".$this->categoryid."'";
			
			return $ob->updateData($conn,$this->Table,$field,$value,$where);
		}
	}
	
	
	function delete($conn)
	{
		$ob=new ClassConnect();	
		
		if(count($this->getChild())==0)
		{
			$where="categoryid = '".$this->categoryid."'";
			return $ob->deleteData($conn,$this->Table,$where);
		}
		
			
	}
	
}
?>
